<template>
    <div class="app-container">
        <el-form :model="postForm" :rules="rules" ref="postForm" label-width="100px" style="width: 80%;">
            <el-form-item label="课程名称" v-if="courseName">
                <el-input v-model="courseName" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="音频名称" prop="name">
                <el-input v-model="postForm.name"></el-input>
            </el-form-item>
            <el-form-item label="音频文件" prop="orgAudioUrl">
                <el-upload
                        :action="actionUrl"
                        :drag="true"
                        :multiple="false"
                        :with-credentials="true"
                        :show-file-list="true"
                        accept="audio/*"
                        :on-success="handleSuccess"
                        :on-error="handleError"
                        :before-upload="beforeUpload"
                        >
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip" v-if="!isUploading">只能上传mp3/m4a文件，文件最大50MB</div>
                    <div class="el-upload__tip" slot="tip" v-if="isUploading">正在上传中...</div>
                </el-upload>
                <el-input v-model="postForm.orgAudioUrl" hidden="hidden"></el-input>
                <audio :src="playAudioUrl" v-if="playAudioUrl" id="sqPlayAudio" controls preload="auto"></audio>
            </el-form-item>
            <el-form-item label="免费试听" prop="free">
                <el-switch
                        v-model="postForm.free"
                        on-color="#13ce66"
                        off-color="#ff4949"
                        :on-value="1"
                        :off-value="0">
                </el-switch>
            </el-form-item>
            <el-form-item label="排序号" prop="serial">
                <el-input v-model.number="postForm.serial"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button v-loading="loading" type="primary" @click="onSubmit">保存</el-button>
                <el-button @click="goBack">返回</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>

    import { getDetail, add, update, getPlayUrl } from '@/api/audio';
    import { getDetail as getCourseDetail } from '@/api/course';

    export default {
        data() {
            return {
                loading: false,
                actionUrl: process.env.BASE_API + '/common/upload/audio',
                isUploading: false,
                postForm: {
                    id: '',
                    name: '',
                    courseId: '',
                    orgAudioUrl: '',
                    free: 0,
                    status: 1,
                    serial: 1
                },
                rules: {
                    name: [
                        { required: true, message: '音频名称', trigger: 'blur' },
                        { min: 2, max: 32, message: '长度在 2 到 32 个字符', trigger: 'blur' }
                    ],
                    orgAudioUrl: [
                        { required: true, message: '请输入上传音频文件', trigger: 'blur' }
                    ],
                    serial: [
                        { type: 'integer', required: true, message: '请输入序号', min: 1, trigger: 'blur' }
                    ]
                },
                isUpdate: false,
                playAudioUrl: '',
                courseName: ''
            }
        },
        created() {
            const reg = /\/(update|add)\/(\d*)$/
            if (reg.test(this.$route.path)) {
                const type = RegExp.$1;
                const ID = RegExp.$2;
                if (type === 'update') {
                    this.isUpdate = true;
                    this.fetchData(ID);
                } else {
                    this.postForm.courseId = ID;
                    this.getCourseInfo();
                }
            }
        },
        methods: {
            updatePlayUrl() {
                getPlayUrl(this.postForm.orgAudioUrl).then(response => {
                    const audioElement = document.getElementById('sqPlayAudio');
                    if (audioElement) {
                        audioElement.pause();
                    }
                    this.playAudioUrl = response.data;
                }).catch(err => {
                    console.log(err)
                });
            },
            getCourseInfo() {
                const courseID = this.postForm.courseId;
                if (!courseID) {
                    return;
                }
                getCourseDetail(courseID).then(response => {
                    this.courseName = response.data.name;
                }).catch(err => {
                    console.log(err)
                });
            },
            fetchData(ID) {
                getDetail(ID).then(response => {
                    this.postForm.id = response.data.id;
                    this.postForm.name = response.data.name;
                    this.postForm.courseId = response.data.courseId;
                    this.postForm.orgAudioUrl = response.data.orgAudioUrl;
                    this.postForm.free = response.data.free;
                    this.postForm.status = response.data.status;
                    this.postForm.serial = response.data.serial;
                    this.updatePlayUrl();
                    this.getCourseInfo();
                }).catch(err => {
                    console.log(err)
                });
            },
            beforeUpload(file) {
                if (this.isUploading) {
                    return false;
                }
                const reg = /(.mp3|.m4a)$/
                const fileOK = reg.test(file.name);
                if (fileOK) {
                    this.isUploading = true;
                }
                return fileOK;
            },
            handleSuccess(response) {
                if (response.code === 0) {
                    this.postForm.orgAudioUrl = response.data;
                    this.updatePlayUrl();
                }
                this.isUploading = false;
            },
            handleError(error) {
                this.$message({
                    title: '上传失败',
                    message: error,
                    type: 'error',
                    duration: 2000
                });
                this.isUploading = false;
            },
            onSubmit() {
                console.log('submit!');
                const that = this;
                this.$refs.postForm.validate(valid => {
                    console.log(that.$refs.postForm.validate);
                    console.log('valid=' + valid);
                    if (valid) {
                        this.loading = true;
                        if (that.isUpdate) {
                            update(that.postForm).then(response => {
                                if (response.code === 0) {
                                    that.$notify({
                                        title: '成功',
                                        message: '更新成功',
                                        type: 'success',
                                        duration: 2000
                                    });
                                    this.$router.go(-1);
                                } else {
                                    that.$message({
                                        title: '失败',
                                        message: '原因:' + response.msg,
                                        type: 'error',
                                        duration: 3000
                                    });
                                }
                                that.loading = false;
                            }).catch(err => {
                                that.$message({
                                    title: '失败',
                                    message: '原因:' + err.msg ? err.msg : err,
                                    type: 'error',
                                    duration: 3000
                                });
                                that.loading = false;
                            });
                        } else {
                            add(that.postForm).then(response => {
                                if (response.code === 0) {
                                    that.$notify({
                                        title: '成功',
                                        message: '添加成功',
                                        type: 'success',
                                        duration: 2000
                                    });
                                    this.$router.go(-1);
                                } else {
                                    that.$message({
                                        title: '失败',
                                        message: '原因:' + response.msg,
                                        type: 'error',
                                        duration: 3000
                                    });
                                }
                                that.loading = false;
                            }).catch(err => {
                                that.$message({
                                    title: '失败',
                                    message: '原因:' + err.msg ? err.msg : err,
                                    type: 'error',
                                    duration: 3000
                                });
                                that.loading = false;
                            });
                        }
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            goBack() {
                this.$router.go(-1);
            }
        }
    }
</script>